package com.dyzx.hbb.common.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.dyzx.hbb.common.base.PageQuery;
import com.dyzx.hbb.common.base.PageResult;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Map;

/**
 * 列表查询基础控制器
 * 
 * 功能说明：提供列表查询功能的基础控制器实现，是整个控制器层次结构的最底层基类
 * 主要职责：
 * - 定义通用的字段常量
 * - 提供实体类获取的功能
 * - 支持基础的列表查询操作
 * 
 * 设计意图：
 * 作为所有控制器的最基础实现，提供共享的常量和基础功能
 * 
 * @param <S> 服务类型，必须是 IService 的子类
 * @param <T> 实体类型
 * @param <Q> 查询参数类型
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
public abstract class BaseCustomListController<S extends IService<T>, T, Q> {
    private static final String ORGAN_FIELD = "organId";
    private static final String OPRERATOR_FIELD = "operatorId";
    private static final String CREATE_DATE_FIELD = "createDate";
    private static final String UPDATE_DATE_FIELD = "updateDate";
    private static final String STATUS_FIELD = "status";

    private final Class<T> entityClass;

    @SuppressWarnings("unchecked")
    protected BaseCustomListController() {
        this.entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    /**
     * 获取服务
     */
    protected abstract S getBaseService();

    /**
     * 创建分页对象
     * @param pageQuery 分页查询参数
     * @return 分页对象
     */
    protected Page<Map<String, Object>> createPage(PageQuery pageQuery) {

      /*  System.out.println("Page:");
        System.out.println(requestURI);
        JSONObject sort = InitConfig.getSort();*/
      //  return new Page<>(pageQuery.getPage(), pageQuery.getPageSize());
        return pageQuery.toPage();
    }

    /**
     * 构建查询条件
     */
    protected abstract MyLambdaQueryWrapper<T> queryWrapper(Q query);



    /**
     * 分页查询
     */
    @Operation(summary = "分页查询")
    @GetMapping("/list")
    public Result<Map<String, Object>> list( PageQuery pageQuery, Q query) {
        Long organId = SecurityContextHolder.getOrganId();
        Long userId = SecurityContextHolder.getUserId();
        MyLambdaQueryWrapper<T> queryWrapper = queryWrapper(query);
        if (queryWrapper==null){
            queryWrapper = new MyLambdaQueryWrapper<>();
        }
        T entity = createEntity();
        Class<?> aClass = entity.getClass();

            // 方案二：检查字段存在性（需要时使用）
            boolean hasOrganField = Arrays.stream(aClass.getDeclaredFields())
                    .anyMatch(f -> ORGAN_FIELD.equals(f.getName()));

            boolean hasOperatorField = Arrays.stream(aClass.getDeclaredFields())
                    .anyMatch(f -> OPRERATOR_FIELD.equals(f.getName()));
            if(hasOperatorField) {
                System.out.println("hasOperatorField:"+hasOperatorField);
                queryWrapper.userNameSql("operator_id").as("operator_name");
               // queryWrapper.select("operator_id");
            }

        boolean hasCreateDateField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> CREATE_DATE_FIELD.equals(f.getName()));
        if(hasCreateDateField) {
            System.out.println("hasCreateDateField:"+hasCreateDateField);
            queryWrapper.select("create_date");

        }
        boolean hasUpdateDateField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> UPDATE_DATE_FIELD.equals(f.getName()));
        if(hasUpdateDateField) {
            System.out.println("hasUpdateDateField:"+hasUpdateDateField);
            queryWrapper.select("update_date");
        }
        boolean hasStatusField = Arrays.stream(aClass.getDeclaredFields())
                .anyMatch(f -> STATUS_FIELD.equals(f.getName()));
        if(hasStatusField) {
            System.out.println("hasStatusField:"+hasStatusField);
            queryWrapper.select("status");
        }
 /*       if(StringUtils.isEmpty(pageQuery.getSort())){
           *//* if(hasUpdateDateField){
              pageQuery.setSort("update_date:desc");
            }
            else{
                pageQuery.setSort("create_date:desc");
            }*//*
            queryWrapper.orderByDesc("update_date");
        }*/

        if(hasOrganField){
            //  if(SecurityContextHolder.isNotAdmin()) {
            // queryWrapper.apply("organ_id = {0}", organId).or().apply("organ_id IS NULL");
          //  queryWrapper.and(wrapper -> wrapper.apply("organ_id = {0}", organId).or().apply("organ_id IS NULL"));
            queryWrapper.apply(" (organ_id = {0} or organ_id IS NULL)", organId);

            //  }

            queryWrapper.orgNameSql("organ_id").as("organ_name");

        }

        Page<Map<String, Object>> page = getBaseService().pageMaps(createPage(pageQuery), queryWrapper);
        return PageResult.parsePage(page);
    }


    private T createEntity() {
        T entityCopy;
        try {
            entityCopy = entityClass.getDeclaredConstructor().newInstance();

        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
            return null;
        }
        return entityCopy;
    }

}
